package com.itheima.aspect;

import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Component
public class LogAspect {

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.itheima.anno.MyLog)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {

        //获取操作人
        String token = httpServletRequest.getHeader("token");
        Claims claims = JwtUtils.parseJwt(token);
        Integer operateId = (Integer) claims.get("id");

        //获取操作时间
        LocalDateTime operateTime = LocalDateTime.now();

        //获取操作的类名
        String className = joinPoint.getTarget().getClass().getName();

        //获取操作的方法名
        String methodName = joinPoint.getSignature().getName();


        //获取方法参数
        Object[] args = joinPoint.getArgs();
        String methodParams = Arrays.toString(args);

        long begin = System.currentTimeMillis();

        Object result = joinPoint.proceed();
        System.out.println(result);
        //获取返回值
        String returnValue = result.toString();

        long end = System.currentTimeMillis();

        //获取方法执行耗时
        Long costTime = end - begin;

        OperateLog operateLog = new OperateLog(null, operateId, operateTime, className, methodName, methodParams, returnValue, costTime,null);

        operateLogMapper.insert(operateLog);

        return result;

    }
}
